package com.beiding.hotcode;

import java.lang.reflect.Method;

public class InstanceLifecycleReflect extends InstanceLifecycle {

    private Method afterCreate;
    private Method beforeAbandon;

    private Object obj;

    public InstanceLifecycleReflect(Object obj) {
        if (obj == null) {
            throw new RuntimeException("代理不能为空");
        }
        this.obj = obj;

        try {
            afterCreate = obj.getClass().getMethod("afterCreate", Object.class);
            beforeAbandon = obj.getClass().getMethod("beforeAbandon", Object.class);
        } catch (Exception e) {
            throw new RuntimeException("afterCreate(Object.class)或beforeAbandon(Object.class)方法");
        }

    }

    @Override
    protected void onAfterCreate(MyInstance realInstance) {
        try {
            afterCreate.invoke(obj, realInstance);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void onBeforeAbandon(MyInstance realInstance) {
        try {
            beforeAbandon.invoke(obj, realInstance);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
